<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="会员昵称" prop="advMembersId">
        <el-select v-model="queryParams.advMembersId" placeholder="会员昵称" :clearable="true">
            <el-option
                v-for="item in membersList"
                :key="item.advMembersId"
                :label="item.memberName"
                :value="item.advMembersId">
            </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单号" prop="ordersno">
        <el-input
          v-model="queryParams.ordersno"
          placeholder="请输入订单号"
          clearable
        />
      </el-form-item>
      <el-form-item label="年份" prop="calYear">
        <el-input-number controls-position="right" v-model="queryParams.calYear" placeholder="请输入年份"></el-input-number>
      </el-form-item>
      <el-form-item label="审核状态" prop="isAudit">
        <el-select v-model="queryParams.isAudit" placeholder="会员状态" clearable>
          <el-option 
              v-for="dict in dict.type.adv_income_is_audit"
              :label="dict.label" 
              :value="dict.value"
              :key="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="月份" prop="calMonth">
        <el-select v-model="queryParams.calMonth" placeholder="选择月份" :clearable="true">
            <el-option
                v-for="item in 12"
                :key="item"
                :label="item"
                :value="item">
            </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:role:add']"
        >结算生成</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:role:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete2"
          v-hasPermi="['system:role:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          size="mini"
          :disabled="multiple"
          v-hasPermi="['system:role:edit']"
          @click="handleBatchUpdate"
        >批量审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          size="mini"
          :disabled="multiple"
          @click="handleShare"
          v-hasPermi="['system:role:export']"
        >批量分账</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:role:export']"
        >导出</el-button>
      </el-col>
  
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="会员昵称" align="center" prop="memberName">
        <!-- <template slot-scope="scope">
          {{ getMembersNickName(scope.row.advMembersId) }}
        </template> -->
      </el-table-column>
      <el-table-column label="年份" align="center" prop="calYear" />
      <el-table-column label="月份" align="center" prop="calMonth" >
        <template slot-scope="scope">
          {{ scope.row.calMonth ? scope.row.calMonth : '/' }}
        </template>
      </el-table-column>
      <el-table-column label="结算类型" align="center" prop="calMode" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.adv_orders_cal_model" :value="scope.row.calMode"/>
        </template>
      </el-table-column>
      <el-table-column label="日结结算日期" align="center" prop="calDate">
        <template slot-scope="scope">
          {{ scope.row.calDate ? scope.row.calDate : '/' }}
        </template>
      </el-table-column>
      <el-table-column label="佣金比例（%）" align="center" prop="taxRate" />
      
      <!-- <el-table-column label="本人订单佣金" align="center" prop="totalAmount" />
      <el-table-column label="下级订单佣金" align="center" prop="totalAmountSub" /> -->
      <el-table-column label="佣金总金额" align="center" prop="payAmount" />
      <el-table-column label="审核状态" align="center" prop="isAudit" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.adv_income_is_audit" :value="scope.row.isAudit"/>
        </template>
      </el-table-column>
      <el-table-column label="分账状态" align="center" prop="isSendcash" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.adv_is_sendcash" :value="scope.row.isSendcash"/>
        </template>
      </el-table-column>
      <el-table-column label="分账日期" align="center" prop="senccashDate" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="230px" >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:role:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:role:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleSolid(scope.row)"
            v-hasPermi="['system:role:remove']"
          >查看明细</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-close"
            @click="handleStop(scope.row, 1)"
            v-hasPermi="['system:role:remove']"
            v-if="scope.row.isAudit != 1 && scope.row.isSendcash==0"
          >审核通过</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-close"
            @click="handleStop(scope.row, 0)"
            v-hasPermi="['system:role:remove']"
            v-if="scope.row.isAudit != 0 && scope.row.isSendcash==0"
            >审核拒绝</el-button>
            <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-close"
            @click="handleStop(scope.row, 2)"
            v-hasPermi="['system:role:remove']"
            v-if="scope.row.isAudit != 2 && scope.row.isSendcash==0"
            >取消审核</el-button>
            <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-close"
            @click="handleOpenShare(scope.row)"
            v-hasPermi="['system:role:remove']"
            v-if="scope.row.isAudit == 1 && scope.row.isSendcash==0"
            >分账转款</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
    v-show="total>0"
    :total="total"
    :page.sync="queryParams.pageNum"
    :limit.sync="queryParams.pageSize"
    @pagination="getList"
  />

    <!-- 结算生成 -->
    <el-dialog :title="title" :visible.sync="settlementFormOpen" width="500px" append-to-body>
      <el-form ref="settlementForm" :model="settlementForm" :rules="rules" label-width="80px">
        <el-form-item label="结算类型" prop="calModel">
          <el-radio-group v-model="settlementForm.calMode" @input="calModelChange">
              <el-radio v-for="dict in dict.type.adv_orders_cal_model" 
                        :label="dict.value" :key="dict.value">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="日结日期" prop="calDate" v-if="settlementForm.calMode === '1'">
          <el-date-picker 
            v-model="settlementForm.calDate" 
            type="date" 
            placeholder="日期"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="月结年份" prop="calYear" v-if="settlementForm.calMode === '2'">
          <el-input-number controls-position="right" v-model="settlementForm.calYear" placeholder="请输入年份"></el-input-number>
        </el-form-item>
        <el-form-item label="月结月份" prop="calMonth" v-if="settlementForm.calMode === '2'">
          <el-select v-model="settlementForm.calMonth" placeholder="选择月份">
              <el-option
                  v-for="item in 12"
                  :key="item"
                  :label="item"
                  :value="item">
              </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="佣金比例" prop="taxRate">
          <el-input v-model="settlementForm.taxRate" placeholder="请输入佣金比例" style="width: 220px">
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSettlementForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 表格数据修改 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="佣金比例" prop="taxRate">
          <el-input v-model="form.taxRate" placeholder="请输入佣金比例"></el-input>
        </el-form-item>
        <el-form-item label="应付金额" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入应付金额"></el-input>
        </el-form-item>
        <el-form-item label="已付金额" prop="payAmount">
          <el-input v-model="form.payAmount" placeholder="请输入已付金额"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    
    <el-dialog title="收益明细" :visible.sync="open1" width="800px" append-to-body>
      <el-table :data="roleList1" style="width: 100%">
        <el-table-column label="订单编号" prop="ordersno" />
        <el-table-column label="订单金额" prop="orderAmount" />
        <el-table-column label="佣金比例（%）" prop="taxRate" />
        <el-table-column label="会员" prop="advMembersId" >
          <template slot-scope="scope">
            {{ getMembersNickName(scope.row.advMembersId) }}
          </template>
        </el-table-column>
        <el-table-column label="订单日期" prop="advOrdersdate" />
      </el-table>
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage4"
      :page-sizes="[10, 200, 300, 400]"
      :page-size="10"
      layout="total, sizes, prev, pager, next, jumper"
      align="right"
      :total="1">
    </el-pagination>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 批量审批窗口 -->
    <el-dialog :title="title" :visible.sync="batchOpen" width="500px" append-to-body>
      <el-form ref="batchData" :model="batchData" :rules="rules" label-width="80px">
        <el-form-item label="审批状态" prop="isAudit">
          <el-radio-group v-model="batchData.isAudit">
            <el-radio :label="1">审核通过</el-radio>
            <el-radio :label="0">审核拒绝</el-radio>
            <el-radio :label="2">取消审核</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBatch">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分账窗口 -->
    <el-dialog :title="title" :visible.sync="shareOpen" width="500px" append-to-body>
      <el-form ref="shareData" :model="shareData" :rules="rules" label-width="80px">
        <el-form-item label="会员ID" prop="advMembersId" hidden="hidden">
          <el-input v-model="shareData.advMembersId" placeholder="会员ID" disabled ></el-input>
        </el-form-item>
        <el-form-item label="会员名称" prop="memberName">
          <el-input v-model="shareData.memberName" disabled ></el-input>
        </el-form-item>
        <el-form-item label="佣金比例" prop="taxRate">
          <el-input v-model="shareData.taxRate" placeholder="请输入佣金比例" disabled></el-input>
        </el-form-item>
        <el-form-item label="应付金额" prop="totalAmount">
          <el-input v-model="shareData.totalAmount" placeholder="请输入应付金额" disabled></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitShare">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量分账 -->
    <el-dialog :title="title" :visible.sync="batchshareOpen" width="500px" append-to-body>
      <p>是否确定进行批量分账</p>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBatchShare">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    
  </div>
</template>

<script>
import { settleaccount, getIncome, listIncome, updateIncome, delIncome, batchSelect, payShare,batchPayShare } from '@/api/server/income.js'
import { listMembers, addMembers, updateMembers, delMembers } from '@/api/server/members.js'
import { detail } from '@/api/server/incomedetail.js' 

export default {
  dicts: ['adv_orders_cal_model', 'adv_income_is_audit','adv_is_sendcash'],
  data() {
    return {
      batchOpen: false,
      batchshareData: {},
      shareData: {},
      shareOpen: false, 
      selectedRows:[],
      batchData: {
        isAudit: 1
      },
      batchOpen: false,
      membersList: [],
      settlementFormOpen: false,
      // 结算提交表格
      settlementForm: {
        calMode: '1',
        calYear: '2024'
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        calYear: '2024'
      },
      open1: false,
      showSearch: true,
      single: false,
      multiple: false,
      loading: false,
      currentPage4: 1,
      roleList: [],
      total: 0,
      title: "",
      open: false,
      form: {},
      roleList1: [],
      rules1: {},
      rules: {
        taxRate: [
          { required: true, message: "请输入佣金比例", trigger: "blur" }
        ],
        totalAmount: [
          { required: true, message: "请输入应付金额", trigger: "blur" }
        ],
        payAmount: [
          { required: true, message: "请输入已付金额", trigger: "blur" }
        ],
        calDate: [
          { required: true, message: "请选择结算日期", trigger: "blur" }
        ],
        calYear: [
          { required: true, message: "请输入结算年份", trigger: "blur" }
        ],
        calMonth: [
          { required: true, message: "请选择结算月份", trigger: "blur" }
        ]
      },
    }
  },
  created() {
    this.getList();
    this.getMembers();
  },
  methods: {
    handleDelete2(){
      if (!this.selectedRows.length) {
        this.$message.error('请选择至少一项进行批量分账');
        return;
      }
      const invalidSelection = this.selectedRows.some(row => row.isAudit != 2);
      if (invalidSelection) {
        this.$message.error('只能删除审核状态为取消审核的条目');
        return;
      }
      this.$confirm('此操作将永久删除该结算数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delIncome(this.ids.join(',')).then((response) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getList();
        }).catch((error) => {
          this.$message({
            type: 'error',
            message: '删除失败!'
          });
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    submitBatchShare(){
      batchPayShare(this.ids).then((response) => {
        this.batchshareOpen = false;
        this.getList();
          this.$message({
            type: 'success',
            message: "提交成功"
          });
          this.batchshareOpen = false;
      })
    },
    handleShare(){
      if (!this.selectedRows.length) {
        this.$message.error('请选择至少一项进行批量分账');
        return;
      }
      this.title = "批量分账";
      this.batchshareOpen = true;
    },
    submitShare(){
      console.log("submit---->",this.shareData);
      payShare(this.shareData).then((response) => {
          this.getList();
          this.$message({
            type: 'success',
            message: "提交成功"
          });
          this.shareOpen = false;
      })
    },
    handleOpenShare(row){
      this.title = "确认分账";
      this.shareData = row;
      this.shareOpen = true;
      this.shareData.memberName = this.getMembersNickName(row.advMembersId);
      console.log("row---->",row);
      console.log("shareData---->",this.shareData);
    },
    handleBatchUpdate() {
      if (!this.selectedRows.length) {
        this.$message.error('请选择至少一项进行批量修改');
        return;
      }
       // 判断是否存在已分账的记录
      const hasSendcash = this.selectedRows.some(row => row.isSendcash == 1);
      if(hasSendcash){
        this.$message.error('选择的条目中有已经分账的数据');
        return;
      }
      this.title = "批量审批";
      this.batchOpen = true;
      },
    //提交
    submitBatch(){
      if (!this.selectedRows.length) {
      this.$message({
        type: 'warning',
        message: '请先选择要审批的记录'
      });
      return;
    }
    
    const isAudits = this.batchData.isAudit;
    const ids = this.selectedRows.map(row => row.advIncomeId);
    
    batchSelect({ ids, reboottime: isAudits }).then(response => {
        this.$message({
          type: 'success',
          message: '提交成功!'
        });
        this.batchOpen = false;
        this.getList();
    });
    },

    // 获取所有会员
    getMembers() {
      listMembers(this.queryParams).then(result => {
        this.membersList = result.rows
      })
    },
    // 根据id获得会员名称
    getMembersNickName(id) {
      for (var i = 0; i < this.membersList.length; i++) {
        if(this.membersList[i].advMembersId == id) {
          return this.membersList[i].memberName
        }
      }
    },
    // 结算类型发生改变
    calModelChange(value) {
      this.settlementForm = {
        calMode: value,
        calYear: '2024'
      }
    },
    // 提交结算表格
    submitSettlementForm() {
      settleaccount(this.settlementForm).then((response) => {
        if(response.statusCode == 200) {
          this.$message({
            type: 'success',
            message: response.message
          });
          this.settlementFormOpen = false;
          this.getList();
        } else {
          this.$message({
            type: 'error',
            message: response.message
          });
        }
      })
    },
    handleQuery() {
      this.getList();
    },
    resetQuery() {},
    handleExport() {
      this.download('/system/income/export', {
        ...this.queryParams
      }, `结算列表_${new Date().getTime()}.xlsx`)
    },
    getList() {
      listIncome(this.queryParams).then((response) => {
        this.roleList = response.rows;
        console.log("getList--->",response);
        this.total = response.total;
      })
    },
    handleSelectionChange() {},
    cancel() {
      this.form = {};
      this.settlementForm = {
        calMode: '1',
        calYear: '2024'
      };
      this.ipe = false;
      this.open1 = false;
      this.batchOpen = false;
      this.batchshareOpen = false;
      this.open = false;
      this.shareOpen = false;
      this.settlementFormOpen = false;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
      this.ids = selection.map(item => item.advIncomeId);
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset();
      this.settlementFormOpen = true;
      this.title = "结算生成";
    },
    handleUpdate(row) {
      this.reset();
      this.form = row;
      this.open = true;
      this.title = "修改审核信息";
    },
    reset() {
      this.form = {
        nickname: "",
        username: "",
        parentUsername: "",
        status: "",
        isAnchor: ""
      }
    },
    handleDelete(row) {
      if(row.isAudit!=2){
        this.$message.error('只能删除审核状态为取消审核的条目');
        return;
      }
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delIncome(row.advIncomeId).then((response) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getList();
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          updateIncome(this.form).then((response) => {
            this.$message({
              type: 'success',
              message: '提交成功!'
            });
            this.open = false;
            this.getList();
          }) 
        } else {
          this.$message({
            type: 'error',
            message: '表单验证失败!'
          });
        }
      })
    },
    handleSolid(row) {
      this.open1 = true
      detail(row.advIncomeId).then((response) => {
        console.log(response)
        this.roleList1 = response.rows
      })
    },
    handleStop(row, status) {
      this.$confirm('确认提交', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        row.isAudit = status;
        updateIncome(row).then((response) => {
          this.$message({
            type: 'success',
            message: '提交成功'
          });
        })
        this.getList();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消禁用'
        });
      });
    },
    
  }
}
</script>

<style>

</style>

